package io.adminboot.service.impl;

import com.google.gson.Gson;
import io.adminboot.domain.vo.PageVO;
import io.adminboot.entity.SysConfig;
import io.adminboot.entity.SysConfigExample;
import io.adminboot.exception.MyException;
import io.adminboot.repository.extend.SysConfigExtMapper;
import io.adminboot.service.SysConfigService;
import io.adminboot.system.cache.SysConfigCache;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

@Service("sysConfigService")
public class SysConfigServiceImpl implements SysConfigService {
	
	@Autowired
	private SysConfigExtMapper mapper;
	@Autowired
	private SysConfigCache sysConfigRedis;

	@Override
	public PageVO queryPage(Integer pageNum, Integer pageSize) {
		List<SysConfig> list = mapper.selectList((pageNum - 1) * pageSize, pageSize);
		int totalCount = mapper.count();
		PageVO page = new PageVO(list, totalCount, pageSize, pageNum);
		return page;
	}
	
	@Override
	public void save(SysConfig config) {
		mapper.insert(config);
		sysConfigRedis.saveOrUpdate(config);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void update(SysConfig config) {
		mapper.updateByPrimaryKey(config);
		sysConfigRedis.saveOrUpdate(config);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateValueByKey(String key, String value) {
		mapper.updateValueByKey(key, value);
		sysConfigRedis.delete(key);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void batchDelete(Long[] ids) {
		for(Long id : ids){
			SysConfig config = this.selectById(id);
			sysConfigRedis.delete(config.getKey());
		}

		mapper.batchDelete(Arrays.asList(ids));
	}

	@Override
	public String getValue(String key) {
		SysConfig config = sysConfigRedis.get(key);
		if(config == null){
			SysConfigExample example = new SysConfigExample();
			example.createCriteria().andKeyEqualTo(key);
			List<SysConfig> list = mapper.selectByExample(example);
			if (list != null && list.size() > 0) {
				config = list.get(0);
			}
			
			sysConfigRedis.saveOrUpdate(config);
		}

		return config == null ? null : config.getValue();
	}
	
	@Override
	public <T> T getConfigObject(String key, Class<T> clazz) {
		String value = getValue(key);
		if(StringUtils.isNotBlank(value)){
			return new Gson().fromJson(value, clazz);
		}

		try {
			return clazz.newInstance();
		} catch (Exception e) {
			throw new MyException("获取参数失败");
		}
	}

	@Override
	public SysConfig selectById(Long id) {
		return mapper.selectByPrimaryKey(id);
	}

}
